package com.cgc999.host.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * @CreateDate: 2020/1/8 18:19
 * @Description: java类作用描述
 * @Author: lgh
 */
public class JavaScriptMethods {
    public static String JSINTERFACE = "jsInterface";
    private Activity mActivity;
    private WebView mWebView;
    private Context mContext;
    public  static final int TAKE_PHOTO = 1000;
    public JavaScriptMethods(Activity activity, Context context, WebView webView) {
        mActivity = activity;
        mWebView = webView;
        mContext = context;
    }

    public String filePath = Environment.getExternalStorageDirectory() + File.separator + "myH5camera" + File.separator + "aaa.jpg";

    @JavascriptInterface
    public void takePhoto() {
//        调用系统摄像头
        Log.i("JavaScriptMethods","startCamera");
        Log.d("调用前置摄像头：","");
//        startCamera(TAKE_PHOTO, filePath);
        startAlbum();
    }

    private void startAlbum(){
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        mActivity.startActivityForResult(intent, 2);
    }

    private void startCamera(int type, String imgName) {
        File filePath = new File(imgName);
        try {
            if (!filePath.exists()) {
                filePath.getParentFile().mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri imageUri;
        /**
         * android7.0及以上
         */
        if (Build.VERSION.SDK_INT >= 24) {
            imageUri = FileProvider.getUriForFile(mContext, mActivity.getPackageName() + ".provider", filePath);
        } else {
            imageUri = Uri.fromFile(filePath);
        }
        //启动相机程序
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        mActivity.startActivityForResult(intent, type);
    }

}
